<template>
	<el-container v-if="isReady">
	  <el-header>
		<div class="left-panel">
		  <fsButton ref="button" plain size="default" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
		</div>
		<div class="right-panel">
			<ex-search v-if="isReady" ref="search" :searches="searches" @searchOk="searchHandler" default-code="code" placeholder="请输入单据编码" :fixedParam="{documentConfigId:this.documentConfigId,manageDeptIds:this.manageDeptIds}"></ex-search>
		</div>
	  </el-header>
	  <el-main class="nopadding" style="overflow: hidden;">
			<ex-table :id="'documentTable'+this.documentConfigId" ref="table" :columns="columns" :url="this.$API.asset.document.list.url" :refs="this.$refs" search="search" @columnClick="columnClickHandler"></ex-table>
	  </el-main>
	</el-container>

	<view-dialog ref="viewDialog"/>

  </template>

  <script>
 import saveDialog from './save.vue'
 import viewDialog from './view'
  import ExTable from "@/components/exTable/index.vue";
  import ExSearch from "@/components/exSearch/index.vue";
  import ExTreeNavigation from "@/components/exSearchTree/index.vue";
  import ExSearchTree from "@/components/exSearchTree/index.vue";
 import cache from "@/utils/cache";
 import formRule from "@/utils/formRule";
 import useTabs from "@/utils/useTabs";
 import {DOCUMENT_STATUS} from "@/utils/StaticConstant";
 import BaseTemplate from "@/utils/baseTemplate";
  //import dict from "@/utils/dict";

  export default {
	name: '单据信息列表',
	components: {
	  ExSearchTree,
	  ExTreeNavigation,
	  ExSearch,
	  ExTable,
	  saveDialog,
	  viewDialog
	},
	data() {
	  return {
		dialog: {
		  save: false,
		  permission: false,
		},
		apiObj: [],
		buttons: [
		 {name: this.$t('button.add'), icon: "el-icon-plus", click: "add", permission: "add"},
        {name: this.$t('button.delete'), icon: "el-icon-delete", click: "del", type: "info",permission: "delete"},
        // {name: this.$t('button.enabled'), icon: "el-icon-circle-check", click: "enabled", type: "success"},
        // {name: this.$t('button.disabled'), icon: "el-icon-circle-close", click: "disabled", type: "info"},
        {name: this.$t('button.export'), icon: "el-icon-download", click: "export", type: "info",permission: "export"},
        //{name: this.$t('button.edit'), icon: "el-icon-edit", type: "parent",parent:true,
        //childrenbuttons:[
        //  {name: this.$t('button.delete'),  click: "del"},
        //  {name: this.$t('button.export'),  click: "export"},
        //]},
		],
		searches: [
		  {type: "input", name: "单据编码", code: "code", placeholder: "请输入编码", maxlength: 30,showLimit: true},
		  {type: "select", name: "处理方式", code: "processTypeId", placeholder: "请选择处理方式", ops: this.processTypes},
		  {type: "selector", name: "制单人", code: "createUser", placeholder: "请选择制单人", dictCode:'SysUser',priKey:true},
		  {type: "tree-select", name: "制单部门", code: "createOrganizationIds", placeholder: "请选择制单部门", dictCode:'SysOrganization',priKey:true,checkStrictly:true,multiple:true,dataPermissionProcess:true,permissionData:this.$TOOL.current.manageDeptIds()},
		  {type: "select", name: "单据状态", code: "statusList", placeholder: "请选择单据状态", dictCode:'DOCUMENT_STATUS',multiple:true},
		  //{type: "checkbox", name: "多选", code: "checkBoxType",ops: this.getOptionData()},
		],
		columns: [
		  {code: "status", name: "单据状态",sortable: true,formatter:"DICT",key: "DOCUMENT_STATUS"},
		  {code: "code", name: "单据编码",click:"show",sortable:true,iscode:true},
		  {code: "documentConfigId", name: "单据名称",formatter:"DICT",key: "FamsDocumentConfig"},
		  {code: "amount", name: "单据总金额", width:"",iscode:true},
		  {code: "processTypeId", name: "处理方式",formatter: "DICT",key: "FamsDocumentProcessType"},
		  {code: "createUser", name: "制单人",formatter: "DICT",key: "SysUser",iscode:true},
		  {code: "createOrganizationId", name: "制单部门",formatter: "DICT",key: "SysOrganization"},
		  {code: "createTime", name: "制单时间",sortable:true,formatter: "DATETIME"},
		],
		parentLevelCode:"",
		documentConfigId:null,
		  manageDeptIds:this.$TOOL.current.manageDeptIds(),
		isReady:false,
		processTypes:[],
	  }
	},
	async created() {
		try {
			this.documentConfigId = this.$route.meta.relTemplateId;
			this.processTypes = await this.$cache.data.loadDocumentProcessType(this.documentConfigId);
			this.searches.filter(item=>item.code === 'processTypeId')[0].ops = this.processTypes;
			//读取配置信息
			let documentConfig = await this.$cache.data.loadDocumentConfig(this.documentConfigId);
			let card = await this.$cache.data.loadDataCard(documentConfig.queryCardId);
      if(card){
        this.columns = card.modules[0].widgets[0].props.columns;
        this.columns.forEach(column=>{
          formRule.updateColumnFormatter(column);
        });
      }
			this.isReady = true;
		}catch (err){
			this.$message.error(this.$t('common.config_error'));
			useTabs.close();
		}
	},
	mounted() {
	},
	methods: {
	  buttonHandler(index, name) {
		this.$options.methods[name](this, index);
	  },
	  async searchTreeHandler(data) {
		let queryParams = {pathCode:data.levelCode}
		this.parentLevelCode=data.levelCode;
		await this.$refs.table.refresh(queryParams);
	  },
	  async searchHandler() {
		  let queryParams = {pathCode: this.parentLevelCode}
		  await this.$refs.table.refresh(queryParams);
	  },
	  columnClickHandler(name,data){
		this.$options.methods[name](this, data);
	  },
	  //添加
	  async add(_this) {
		  // let data = {
		  //   parentLevelCode: _this.parentLevelCode,
		  //   entityName:_this.$CONSTANT.entity.FamsColumn.name,
		  // };
		  // _this.$nextTick(() => {
		  //   _this.$refs.saveDialog.open(data);
		  // })
		  // console.log(_this.$route);

		  // let route = _this.$router.resolve({name: 'documentPrepare'});
		  // _this.$router.resolve({name: _this.$route.name}).children.push(route);
		  // _this.$router.addRoute(_this.$route.name,route);
		  // console.log(_this.$router.resolve({name: _this.$route.name}));
		  // _this.$TOOL.crypto.MD5(_this.$route.path)
		  let documentConfig = await _this.$cache.data.loadDocumentConfig(_this.documentConfigId);
		  if(documentConfig.type==='permission'){
			  let confirm = await _this.$confirm('新增权限转移单将锁定您的所有审批权限，请谨慎新增权限转移单，单据执行完成或删除后会自动解锁审批权限，请确认是否新增权限转移单?', '提示', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
			  if (!confirm) return;
		  }
		  _this.$router.push({name:"documentPrepare",params:{fromRouteId:_this.$TOOL.crypto.MD5(_this.$route.path),configId:_this.documentConfigId}});
	  },
	//查看
	show(_this,row) {
		_this.$nextTick(() => {
			_this.$router.push({name:"documentPrepare",params:{fromRouteId:_this.$TOOL.crypto.MD5(_this.$route.path),configId:_this.documentConfigId,id:row.id}});
		})
	},
	//查看Oa单据
	async showOa(_this, row) {
		if (row.other && row.other.piid) {
			let oaServerUrl = "https://www.gtja.net/flowweb/EOA/EOA001";
			let oaDocumentServerUrl = await _this.$TOOL.oaDocumentServerUrl();
			const element = document.createElement('a')
			element.setAttribute('href', oaServerUrl + "?piid=" + row.other.piid);
			element.setAttribute('target', "_blank")
			element.style.display = 'none'
			element.click()
		} else {
			_this.$message.warning("尚未提交到OA");
		}
	},
    //导出
    async export(_this,index) {
      let attachParams = {};
      let exportApi = _this.$API.asset.document.export;
      let exTableRef = _this.$refs.table;
      let exportBtnRef = _this.$refs.button;
      let exportBtnIndex = index;
      await BaseTemplate.export(_this, exportApi, attachParams, exportBtnRef, exportBtnIndex, exTableRef);

    },
	  //批量删除
	  del(_this, index) {
      let selections = _this.$refs.table.selections();
      if (selections.length === 0) {
        _this.$message.warning(_this.$t("common.please_select_data"));
        return;
      }
	  let delarray = [];
	  for (let index = 0; index < selections.length; index++) {
		  const element = selections[index];
		  if(element.status!==DOCUMENT_STATUS.PREPARING){
			  //_this.$message.error("单据已提交,不允许删除");
			  continue;
		  }
		  if(element.createUser!==_this.$TOOL.current.user().id){
			  //_this.$message.error("非本人创建的单据,不允许删除");
        continue;
		  }
      delarray.push(element.id);
	  }
    if(delarray.length==0){
      _this.$message.error("请选择本人创建的制单中单据删除");
      return;
    }

      _this.$confirm(`是否删除单据?`, '提示', {
        type: 'warning'
      }).then(async () => {
        _this.$refs.button.loading(index, true);
        var res = await _this.$API.asset.document.deleteByIds.post(delarray);
        if (res.code === 2000) {
          _this.$message.success(_this.$t("code."+res.code));
          _this.searchHandler();
		  _this.$store.dispatch("commit",selections[0].entityName);
        }
        _this.$refs.button.loading(index, false);
      }).catch(() => {
        _this.$refs.button.loading(index, false);
      });
    },
    //批量启用
    enabled(_this, index) {
      let selections = _this.$refs.table.selections();
      if (selections.length === 0) {
        _this.$message.warning(_this.$t("common.please_select_data"));
        return;
      }
      _this.$confirm(`确定启用选中的 ${selections.length} 项吗？`, '警告', {
        type: 'warning'
      }).then(async () => {
        _this.$refs.button.loading(index, true);
        var delarray = [];
        for (let index = 0; index < selections.length; index++) {
          const element = selections[index];
          delarray.push(element.id);
        }
        var res = await _this.$API.asset.document.enabled.post(delarray);
        if (res.code === 2000) {
          _this.$message.success(_this.$t("code."+res.code));
          _this.searchHandler();
		  _this.$store.dispatch("commit",selections[0].entityName);
        }
        _this.$refs.button.loading(index, false);
      }).catch(() => {
        _this.$refs.button.loading(index, false);
      });
    },
    //批量禁用
    disabled(_this, index) {
      let selections = _this.$refs.table.selections();
      if (selections.length === 0) {
        _this.$message.warning(_this.$t("common.please_select_data"));
        return;
      }
      _this.$confirm(`确定禁用选中的 ${selections.length} 项吗？`, '警告', {
        type: 'warning'
      }).then(async () => {
        _this.$refs.button.loading(index, true);
        var delarray = [];
        for (let index = 0; index < selections.length; index++) {
          const element = selections[index];
          delarray.push(element.id);
        }
        var res = await _this.$API.asset.document.disabled.post(delarray);
        if (res.code === 2000) {
          _this.$message.success(_this.$t("code."+res.code));
          _this.searchHandler();
		  _this.$store.dispatch("commit",selections[0].entityName);
        }
        _this.$refs.button.loading(index, false);
      }).catch(() => {
        _this.$refs.button.loading(index, false);
      });
	  },
	}
  }
  </script>
